<script setup lang="ts">
import imageData from './composables/imageData'
import Tip from './components/Tip.vue'
import { getHospitalsAPI, getHosNameAPI } from '@/api/hosp'
import { getDictionaryAPI } from '@/api/common'
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

// 搜索框输入内容
const searchInput = ref<string>('')

// 医院列表
const hosListData = ref([])
/** 根据医院名称获取医院列表 */
const getHosName = async (queryString: string, cb: any) => {
  const { data: res } = await getHosNameAPI(queryString)
  if (res.code !== 200) return ElMessage.error(res.message)
  hosListData.value = res.data.map((item: any) => {
    return {
      value: item.hosname, // 医院的名字
      hoscode: item.hoscode, // 医院的唯一标识符
    }
  })
  cb(hosListData.value)
}

/**跳转到详情页 */
const gotoDetail = (item: any) => {
  router.push({
    name: 'Detail',
    query: {
      code: item.hoscode, // 医院的唯一标识符
    },
  })
}

// 分页器当前页数
const currentPage = ref<number>(1)
//  分页器每页显示条数
const pageSize = ref<number>(10)

/** 分页器每页显示条数改变时触发事件 */
const pageSizeChange = (val: number) => {
  currentPage.value = val
  pageSize.value = val
  getHospitals(currentPage.value, pageSize.value)
}
/** 分页器当前页数发生改变时触发事件 */
const currentPageChange = (val: number) => {
  currentPage.value = val
  getHospitals(currentPage.value, pageSize.value)
}

// 医院列表总数据
const hospitalData = ref<any>({})
// 医院总个数
const total = ref<number>(0)
/**获取医院列表 */
const getHospitals = async (page: number, limit: number, param: object = {}) => {
  const { data: res } = await getHospitalsAPI(page, limit, param)
  if (res.code !== 200) return ElMessage.error(res.message)
  hospitalData.value = res.data
  total.value = res.data.totalElements
}

//  保存 根据dictCode获取下级节点 的数据
const dictiomaryData = ref<any>([])
/** 获取医院等级和地区
 * @param dictCode {string} 类型
 */
const getDictionary = async (dictCode: string, title: string = '') => {
  const { data: res } = await getDictionaryAPI(dictCode)
  if (res.code !== 200) return ElMessage.error(res.message)
  dictiomaryData.value.push({
    title,
    data: res.data,
  })
}

enum filterateType {
  hostype = '等级',
  districtCode = '地区',
}

// 获取医院列表的第三个参数对象
const filterateCode = ref<{
  [name: string]: string
}>({
  hosname: searchInput.value,
})

// 监听 searchInput 的变化
watch(searchInput, (newValue) => {
  filterateCode.value.hosname = newValue
})

/**
 * 点击筛选进行筛选
 * @param val 值
 * @param type 类型
 */
const getFilterate = (val: string, type: string) => {
  // 遍历筛选类型对象
  Object.keys(filterateType).forEach((key) => {
    // 检查类型是否匹配
    if (filterateType[key as keyof typeof filterateType] === type) {
      // 检查筛选参数对象中是否存在该属性，并检查属性值是否相等
      if (Object.prototype.hasOwnProperty.call(filterateCode.value, key) && filterateCode.value[key] === val)
        // 如果属性已存在且值相等，则 return 出去,不发送请求
        return
      if (val === '全部') {
        // 如果请求属性值为 全部 要删除该属性
        delete filterateCode.value[key]
      } else {
        // 否则，设置该属性为指定值
        filterateCode.value[key] = val
      }
      // 调用获取医院列表的函数，传入当前页码、页大小和筛选参数对象
      getHospitals(currentPage.value, pageSize.value, filterateCode.value)
    }
  })
}

onMounted(async () => {
  Promise.all([await getDictionary('hostype', '等级'), await getDictionary('Beijin', '地区')])
  Promise.all([getHospitals(currentPage.value, pageSize.value)])
})
</script>

<template>
  <div class="home_container">
    <!-- 首页轮播图 -->
    <el-carousel height="350px">
      <el-carousel-item v-for="item in imageData" :key="item.id">
        <img :src="item.picUrl" alt="轮播图" />
      </el-carousel-item>
    </el-carousel>
    <!-- 搜索 -->
    <div class="search_container">
      <el-autocomplete
        class="autocomplete"
        :trigger-on-focus="false"
        :fetch-suggestions="getHosName"
        clearable
        placeholder="请输入医院名称"
        v-model="searchInput"
        @select="gotoDetail"
      >
        <template #append>
          <el-button icon="Search" @click="getHospitals(currentPage, pageSize, filterateCode)"></el-button>
        </template>
      </el-autocomplete>
    </div>
    <!-- 展示医院 -->
    <el-row :gutter="20">
      <el-col :span="20">
        <div class="hospital_container">
          <!-- 医院筛选 -->
          <Filterate :filterate="dictiomaryData" :title="'医院'" @get-filterate="getFilterate" />
          <!-- 医院列表 -->
          <div class="hospital_list" v-if="hospitalData?.content?.length !== 0">
            <hospital_card
              class="hospital_card"
              v-for="item in hospitalData.content"
              :key="item.id"
              :hospital="{
                title: item.hosname,
                picUrl: item.logoData,
                hospType: item.param.hostypeString,
                releaseTime: item.bookingRule.releaseTime,
                quitTime: item.bookingRule.quitTime,
                hoscode: item.hoscode,
              }"
            />
          </div>
          <!-- 分页器 -->
          <el-pagination
            v-if="hospitalData?.content?.length !== 0"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="currentPageChange"
            @size-change="pageSizeChange"
          />
          <!-- 无数据展示 -->
          <img v-if="hospitalData?.content?.length === 0" src="@/assets/Svg/noList.svg" class="noList" />
        </div>
      </el-col>
      <el-col :span="4">
        <!-- 科室静态搭建 -->
        <Tip></Tip>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.home_container {
  padding: 20px 0;

  .el-carousel {
    .el-carousel__item {
      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  /* 搜索 */
  .search_container {
    width: 800px;
    height: 40px;
    margin: 40px auto;
    display: flex;
    align-items: center;
    justify-content: center;

    :deep(.autocomplete) {
      width: 600px;

      .el-input__inner {
        height: 40px;
      }
    }
  }

  /* 展示医院 */
  .hospital_container {
    margin: 40px auto 0 auto;

    /* 医院列表 */
    .hospital_list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin-bottom: 20px;

      .hospital_card {
        width: 49%;
        margin: 5px 0;
        cursor: pointer;
      }

      .hospital_card:hover {
        transform: translateY(-5px);
      }
    }
    .noList {
      width: 100%;
      height: 400px;
    }
  }
}
</style>
@/api/hosp
